#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <unordered_map>
// 买卖股票的最佳时机 III：https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/description/
using namespace std;
class Solution {
public:
    const int INF=0x3f3f3f3f;
    int maxProfit(vector<int>& prices) {  
        int m=prices.size();
        int n=3;
        vector<vector<int>> f(m,vector<int>(n,-INF));
        auto g=f;
        f[0][0]=-prices[0],g[0][0]=0;
        /*                    //方法1解决越界
        for(int i=1;i<m;i++)   
        {
            g[i][0]=g[i-1][0];
            f[i][0]=max(f[i-1][0],g[i-1][0]-prices[i]);
        }*/
        for(int i=1;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                f[i][j]=max(f[i-1][j],g[i-1][j]-prices[i]);
                //g[i][j]=max(g[i-1][j],f[i-1][j-1]+prices[i]);
                g[i][j]=g[i-1][j];
                if(j-1>=0) g[i][j]=max(g[i][j],f[i-1][j-1]+prices[i]);
            }
        }
        int ret=-INF;
        for(int k=0;k<n;k++)
            ret=max(ret,g[m-1][k]);
        return ret;
    }
};